package com.dtease.agent.common.utils;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
* @description 基于 hutool 的 JdbcUtil
* @author chentl
* @class JdbcUtil
* @package com.dtease.agent.metadata.utils
* @since 2025/5/7 15:37
*/
public class JdbcUtil {

    /**
     * 执行分页查询
     *
     * @param dataSource 数据源
     * @param sql        SQL语句
     * @return 查询结果
     */
    public static List<Entity> queryPage(DataSource dataSource, String sql, int pageNum, int pageSize) {
        String pagedSql = sql + " LIMIT " + (pageNum * pageSize) + ", " + pageSize;
        try {
            return Db.use(dataSource).query(pagedSql);
        } catch (SQLException e) {
            throw new RuntimeException("执行SQL失败: " + pagedSql, e);
        }
    }

    /**
     * 构建数据源
     * @author chentl
     * @since 15:37 2025/5/7
     * @param url url
     * @param user user
     * @param password password
     * @param driver driver
     * @return {@link DataSource}
     **/
    public static DataSource buildDataSource(String url, String user, String password, String driver) {
        try {
            return DataSourceBuilder.create()
                    .url(url)
                    .username(user)
                    .password(password)
                    .driverClassName(driver)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException("构建数据源失败", e);
        }
    }

    /**
     * 执行查询具体sql
     * @author chentl
     * @since 15:37 2025/5/7
     * @param ds ds
     * @param sql sql
     * @return {@link List< Entity>}
     **/
    public static List<Entity> query(DataSource ds, String sql) {
        try {
            List<Entity> list = Db.use(ds).query(sql);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException("执行SQL失败: " + sql, e);
        }
    }
}